var app = getApp();

Page({
    data: {
        prefix: "https://cdn.kaayun.com/",
        vote_type: "",
        date_end: "",
        time_end: "",
        userInfo: {},
        canIUse: wx.canIUse("button.open-type.getUserInfo"),
        hasUserInfo: !1,
        submiting: !1,
        helper_switch: {
            graphic: !1,
            daily: !1,
            share: !1,
            multiple: !1,
            anonymous: !1,
            profile: !1,
            view: !0
        },
        helper_multiple: {
            least: 1,
            most: 2
        },
        helper_top: {
            title: "",
            description: ""
        },
        helper_opts: {
            opts: [ {
                fid: "",
                value: "",
                key: "unique_0"
            }, {
                fid: "",
                value: "",
                key: "unique_1"
            } ],
            unique_helper: 2
        },
        templateSettingIndex: 0,
        templateSettings: [ {
            title: "显示票数"
        }, {
            title: "显示票数和明细"
        }, {
            title: "不显示票数"
        } ],
        description: "",
        checkboxValues: [ "姓名" ],
        checkboxItems: [ {
            name: "姓名",
            value: "姓名",
            checked: !0
        }, {
            name: "手机号",
            value: "手机号"
        }, {
            name: "学号",
            value: "学号"
        }, {
            name: "身份证",
            value: "身份证"
        }, {
            name: "员工号",
            value: "员工号"
        }, {
            name: "微信号",
            value: "微信号"
        }, {
            name: "单位",
            value: "单位"
        }, {
            name: "部门",
            value: "部门"
        }, {
            name: "职位",
            value: "职位"
        }, {
            name: "学校",
            value: "学校"
        }, {
            name: "专业",
            value: "专业"
        }, {
            name: "备注",
            value: "备注"
        } ]
    },
    onLoad: function(e) {
        var a = this;
        this.initDate(e);
        var o = "创建群投票";
        "PK" === e.vote_type && (o = "创建二选一投票"), wx.setNavigationBarTitle({
            title: o
        }),this.setData({
            userInfo: app.globalData.userInfo,
            hasUserInfo: !0
        }) 

    },
    desChange: function(e) {
        this.data.description = e.detail.value;
    },
    inputChange: function(t) {
        this.setData((0, e.default)({}, "helper_opts.opts[".concat(t.currentTarget.dataset.index, "].value"), t.detail.value));
    },
    bindReplaceInput: function(e) {
        var t = e.detail.value;
        return "0" === t ? "1" : t;
    },
    bindTemplateSettingChange: function(e) {
        this.setData({
            templateSettingIndex: Number(e.detail.value)
        });
    },
    voteAddOpt: function() {
        this.data.helper_opts.opts.length < 1e3 ? (this.data.helper_opts.opts.push({
            fid: "",
            value: "",
            key: "unique_" + this.data.helper_opts.unique_helper++
        }), this.setData({
            "helper_opts.opts": this.data.helper_opts.opts
        })) : t.showTip("最多可添加1000个选项。");
    },
    voteDeleteOpt: function(e) {
        this.data.helper_opts.opts.length > 2 ? (this.data.helper_opts.opts.splice(e.currentTarget.dataset.index, 1), 
        this.setData({
            "helper_opts.opts": this.data.helper_opts.opts
        })) : t.showTip("最少2个选项。"), console.error(JSON.stringify(e, null, 5));
    },
    voteUploadImage: function(e) {
        var t = this, a = e.currentTarget.dataset.index;
        this.data.helper_opts.opts[a].fid ? wx.showActionSheet({
            itemList: [ "预览图片", "重新上传" ],
            success: function(e) {
                0 === e.tapIndex && wx.previewImage({
                    urls: [ t.data.prefix + t.data.helper_opts.opts[a].fid ]
                }), 1 === e.tapIndex && t.voteChooseImage(a);
            }
        }) : this.voteChooseImage(a);
    },
    voteChooseImage: function(e) {
        var t = this;
        wx.showActionSheet({
            itemList: [ "拍照", "从手机相册选择", "从微信会话选择" ],
            success: function(a) {
                0 === a.tapIndex && t.voteChooseImageNext([ "camera" ], e), 1 === a.tapIndex && t.voteChooseImageNext([ "album" ], e), 
                2 === a.tapIndex && wx.chooseMessageFile({
                    count: 1,
                    type: "image",
                    success: function(a) {
                        a.tempFiles && a.tempFiles.length > 0 && t.voteChooseImageSuccess(a.tempFiles[0].path, e);
                    }
                });
            }
        });
    },
    voteChooseImageNext: function(e, t) {
        var a = this;
        wx.chooseImage({
            count: 1,
            sizeType: [ "compressed" ],
            sourceType: e,
            success: function(e) {
                a.voteChooseImageSuccess(e.tempFilePaths[0], t);
            },
            fail: function(e) {
                console.error("chooseImage", e);
            }
        });
    },
    voteChooseImageSuccess: function(e, a) {
        var o = this;
        setTimeout(function() {
            wx.showLoading({
                title: "上传中...",
                mask: !0,
                success: function(s) {
                    wx.uploadFile({
                        url: "https://api.kaayun.com/wx/v1/upload",
                        filePath: e,
                        name: "file",
                        formData: {
                            source: "miniprogram_group-vote"
                        },
                        success: function(e) {
                            if (console.error("Upload", e), wx.hideLoading(), 200 === e.statusCode) {
                                try {
                                    e.data = JSON.parse(e.data);
                                } catch (e) {
                                    return t.showTip("上传图片失败。");
                                }
                                switch (e.data.commands.statusCode) {
                                  case "SUCCESS":
                                    o.data.helper_opts.opts[a].fid = e.data.payload.uploadResponse.fid, o.setData({
                                        "helper_opts.opts": o.data.helper_opts.opts
                                    });
                                    break;

                                  case "SIZE":
                                    t.showTip("超过图片大小限制：1M");
                                    break;

                                  case "ERROR_RISKY":
                                    t.showTip("图片包含违规内容（色情、涉政等）");
                                    break;

                                  default:
                                    t.showTip("上传图片失败。");
                                }
                            } else t.showTip("上传图片失败。");
                        },
                        fail: function(e) {
                            console.error(e), wx.hideLoading(), t.showTip("上传图片失败。");
                        }
                    });
                },
                fail: function(e) {}
            });
        }, 500);
    },
    profileChange: function(e) {
        this.setData({
            "helper_switch.profile": e.detail.value
        });
    },
    dailyChange: function(e) {
        this.setData({
            "helper_switch.daily": e.detail.value
        });
    },
    multipleChange: function(e) {
        this.setData({
            "helper_switch.multiple": e.detail.value
        });
    },
    shareChange: function(e) {
        this.setData({
            "helper_switch.share": !e.detail.value
        });
    },
    graphicChange: function(e) {
        this.setData({
            "helper_switch.graphic": e.detail.value
        });
    },
    anonymousChange: function(e) {
        this.setData({
            "helper_switch.anonymous": e.detail.value
        });
    },
    checkboxChange: function(e) {
        for (var a = this.data.checkboxItems, o = e.detail.value, s = [], i = 0, n = a.length; i < n; ++i) {
            a[i].checked = !1;
            for (var l = 0, r = o.length; l < r && l < 3; ++l) if (a[i].value == o[l]) {
                s.push(o[l]), a[i].checked = !0;
                break;
            }
        }
        this.setData({
            checkboxValues: s,
            checkboxItems: a
        }), e.detail.value.length > 3 && t.showTip("最多可加三项信息。");
    },
    onGetUserInfo: function(e) {
        var a = this;
        e.detail.userInfo && t.getEditUserInfo(e.detail.userInfo, function() {
            t.globalData.userInfo = e.detail.userInfo, a.setData({
                userInfo: e.detail.userInfo,
                hasUserInfo: !0
            });
        });
    },
    initDate: function(e) {
        var a = new Date(), o = new Date(a);
        o.setDate(a.getDate() + 1);
        var s = this.initFormatDate(o), i = {};
        if (i.date_end = s.date, i.time_end = s.time, e.copy && t.globalData.formInfo) {
            i.helper_switch = t.globalData.formInfo.helper_switch, i.helper_top = t.globalData.formInfo.helper_top, 
            i.helper_opts = t.globalData.formInfo.helper_opts, i.helper_multiple = t.globalData.formInfo.helper_multiple, 
            i.description = t.globalData.formInfo.helper_top.description, i.templateSettingIndex = t.globalData.formInfo.templateSettingIndex;
            var n = t.globalData.formInfo.checkboxValues;
            if (n && n.length > 0) {
                for (var l = this.data.checkboxItems, r = 0, h = l.length; r < h; ++r) {
                    l[r].checked = !1;
                    for (var u = 0, p = n.length; u < p && u < 3; ++u) if (l[r].value === n[u]) {
                        l[r].checked = !0;
                        break;
                    }
                }
                i.checkboxValues = n, i.checkboxItems = l;
            }
            t.globalData.formInfo = null;
        }
        e.vote_type && (i.vote_type = e.vote_type, "PK" === i.vote_type && (i.templateSettings = [ {
            title: "显示票数"
        }, {
            title: "显示票数和明细"
        } ])), this.setData(i);
    },
    initFormatDate: function(e) {
        var t = e.getFullYear(), a = e.getMonth() + 1, o = e.getDate(), s = e.getHours(), i = e.getMinutes();
        return a < 10 && (a = "0" + a), o < 10 && (o = "0" + o), s < 10 && (s = "0" + s), 
        i < 10 && (i = "0" + i), {
            date: t + "-" + a + "-" + o,
            time: s + ":" + i
        };
    },
    bindDateEndChange: function(e) {
        this.setData({
            date_end: e.detail.value
        });
    },
    bindTimeEndChange: function(e) {
        this.setData({
            time_end: e.detail.value
        });
    },
    formSubmit: function(e) {
        var a = this, o = e.detail.value;
        if (console.error("formSubmit>>>", e), !o.title) return t.showTip("请先输入投票标题。");
        o.description = this.data.description;
        for (var s = 0; s < this.data.helper_opts.opts.length; s++) if (o["opts.".concat(s)] && (o["opts.".concat(s)] = o["opts.".concat(s)].replace(/(^\s*)|(\s*$)/g, "")), 
        !o["opts.".concat(s)]) return t.showTip("第".concat(s + 1, "个选项无有效内容。"));
        if (this.data.helper_switch.graphic) for (var i = 0; i < this.data.helper_opts.opts.length; i++) if (!this.data.helper_opts.opts[i].fid) return t.showTip("第".concat(i + 1, "个选项无图片。"));
        if (this.data.helper_switch.multiple) {
            if (o.least = Number(o.least) || 0, o.most = Number(o.most) || 0, o.least < 1) return t.showTip("最少可选项数不能小于 1");
            if (o.least > o.most) return t.showTip("最少可选项数不能超过最多可选项数。");
            if (o.most > this.data.helper_opts.opts.length) return t.showTip("最多可选项数不能超过总选项数。");
            if (o.most <= 1) return t.showTip("最多可选项数必须大于 1。");
        }
        0 === this.data.templateSettingIndex && (o.view = !0), 1 === this.data.templateSettingIndex && (o.view = !0, 
        o.view_record = !0), o.checkboxValues = this.data.checkboxValues, wx.showModal({
            title: "温馨提示",
            cancelText: "取消",
            confirmText: "确定",
            content: "投票创建后不支持再次修改，请确认无误后提交。",
            success: function(e) {
                e.confirm && (a.setData({
                    submiting: !0
                }), t.requestSubscribeMessage(function(e) {
                    e || (o.tmplIds = t.globalData.tmplIds), a.formSubmitNext(o);
                }));
            }
        });
    },
    formSubmitNext: function(e) {
        for (var a = this, o = [], s = 0; s < this.data.helper_opts.opts.length; s++) o.push(this.data.helper_opts.opts[s].fid);
        wx.showLoading({
            title: "创建中...",
            mask: !0
        }), wx.cloud.callFunction({
            name: "addvote",
            data: t.formatCloudParams({
                form: e,
                fids: o,
                vote_type: this.data.vote_type,
                user_info: t.globalData.userInfo
            }),
            success: function(e) {
                wx.hideLoading(), a.setData({
                    submiting: !1
                }), e.result.error ? t.showTip(e.result.msg) : wx.redirectTo({
                    url: "../voteInfo/voteInfo?id=" + e.result._id
                }), console.log("[数据库] [新增记录] 成功: ", e);
            },
            fail: function(e) {
                wx.hideLoading(), a.setData({
                    submiting: !1
                }), t.showTip("创建失败，请稍后再试。"), console.error("[云函数] [addvote] 调用失败", e);
            }
        });
    },
    onReady: function() {},
    onShow: function() {},
    onHide: function() {},
    onUnload: function() {},
    onPullDownRefresh: function() {},
    onReachBottom: function() {},
    onShareAppMessage: function() {}
});